package com.kx.websocket.interceptor;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import java.util.Map;

/**
 * 拦截器
 * @ClassName MyWebSocketInterceptor
 * @Author Sun
 * @Date 2021/6/1 19:23
 */
@Component
public class MyWebSocketInterceptor extends HttpSessionHandshakeInterceptor {
    /**
     * 握手之前，也就是建立真正的连接之前
     * @param request
     * @param response
     * @param wsHandler
     * @param attributes  websocketsession 的属性
     * @return 返回值代表是否放行
     * @throws Exception
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        //我们约定,请求地址的最后一位就是用户的唯一信息
        String uri = request.getURI().toString();
        //拿到id，也就是谁发送的，每个用户拥有唯一的id
        String name = uri.substring(uri.lastIndexOf("/") + 1);
        //保存到websocketsession的属性中，方便在后边获取
        attributes.put("key", name);
        return super.beforeHandshake(request, response, wsHandler, attributes);
    }

    /**
     * 握手之后
     * @param request
     * @param response
     * @param wsHandler
     * @param ex
     */
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {
        super.afterHandshake(request, response, wsHandler, ex);
    }
}
